package com.captain.special.链表;
import com.captain.leetcode.链表.ListNode;
/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/23 14:51
 */
public class 反转链表2_92 {

    public static void main(String[] args) {
        new 反转链表2_92().reverseBetween(ListNode.getInstance(), 2, 4);
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        //切割为三部分
        //1.计算总的长度
        if (head == null || head.next == null) return head;
        ListNode lengthNode = head;
        int len = 0;
        while (lengthNode != null) {
            len++;
            lengthNode = lengthNode.next;
        }
        //计算左 中 右 节点
        // -1 1 2 3 4 5   2 4  left - 1   5 -
        ListNode dummy = new ListNode(-1, head);

        ListNode cur = dummy;
        //下一个节点开始
        int leftIndex = left - 1;
        // 4 - 2 + 1 = 3
        int interval = right - left + 1;
        while (leftIndex > 0) {
            leftIndex--;
            cur = cur.next;
        }
        //前链表 pre.next 就是中间链表
        ListNode pre = cur;
        while (interval > 0) {
            interval--;
            cur = cur.next;
        }
        ListNode back = cur.next;
        //截断链表
        cur.next = null;
        ListNode mid = pre.next;

        //翻转链表
        mid = flipLinkedList(mid);
        pre.next = mid;
        ListNode curMid = mid;
        while (curMid.next != null) {
            curMid = curMid.next;
        }
        curMid.next = back;
        //记录前一个节点
        return dummy.next;

    }

    private ListNode flipLinkedList(ListNode mid) {
        //操作指针
        ListNode pre = null;
        //1 2 3 4  null
        while (mid != null) {
            ListNode temp = mid.next;
            mid.next = pre;
            pre = mid;
            mid = temp;
        }
        return pre;
    }
}
